package com.lovo;

import com.lovo.config.ApplicationConfig;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.FilterDef;
import org.apache.tomcat.util.descriptor.web.FilterMap;
import org.springframework.orm.hibernate5.support.OpenSessionInViewFilter;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Filter;
import javax.servlet.ServletContext;

public class ApplicationMain {
    public static void main(String[] args) throws LifecycleException {
        // 实例化Tomcat
        Tomcat tomcat = new Tomcat();
        // 设置Tomcat端口
        tomcat.setPort(8080);
        // 引导HTTP引擎
        tomcat.getConnector();
        Context ctx = tomcat.addContext("",null);
        // 添加字符编码的过滤器
        addFilter(ctx,
                "CharacterEncodingFilter",
                new CharacterEncodingFilter("utf-8",true,true),
                "/*");

        WebApplicationContext appCtx = createApplicationContext(ctx.getServletContext());

        // 第二个参数是Servlet名称
        DispatcherServlet dispatcherServlet = new DispatcherServlet(appCtx);
        Wrapper servlet = Tomcat.addServlet(ctx,"DispatcherServlet",dispatcherServlet);
        // 启动初始化Servlet
        servlet.setLoadOnStartup(1);
        // 任何访问路径都能进入该Servlet
        servlet.addMapping("/*");

        // 启动服务器
        tomcat.start();
    }

    public static WebApplicationContext createApplicationContext(ServletContext servletContext) {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(ApplicationConfig.class);


        ctx.setServletContext(servletContext);
        ctx.refresh();
        ctx.registerShutdownHook();
        return ctx;
    }
    public static void addFilter(Context context, String filterName, Filter filter, String urlPattern) {
        FilterDef filterDef = new FilterDef();
        filterDef.setFilter(filter);
        filterDef.setFilterName(filterName);
        FilterMap filterMap = new FilterMap();
        filterMap.setFilterName(filterName);
        filterMap.addURLPatternDecoded(urlPattern);
        context.addFilterDef(filterDef);
        context.addFilterMap(filterMap);
    }


}
